const express = require('express')
const axios = require('axios')
const { get, del, set } = require('../utils/cache')

const router = express.Router()

const CACHE_KEY = 'weibo'
const TITLE = '微博'

router.get('/weibo', async (req, res) => {
    if (req.query.timestamp) {
        del(CACHE_KEY)
    }
    let data = get(CACHE_KEY)
    if (data) {
        res._op('success', 1, data)
        console.log('在缓存中获取');
    }
    else {
        try {
            const { data: result } = await axios.get('https://weibo.com/ajax/statuses/hot_band')
            const list = result.data.band_list.map(v => {
                return {
                    title: v.word,
                    desc: v.note,
                    hotCount: v.raw_hot,
                    url: `https://s.weibo.com/weibo?q=${encodeURIComponent(v.word_scheme ? v.word_scheme : v.word)}`
                }
            })
            const updateTime = new Date().getTime()
            data = {
                title: TITLE,
                total: list.length,
                list,
                updateTime
            }
            set(CACHE_KEY, data)
            res._op('success', 1, data)
            console.log('通过服务获取');
        } catch (error) {
            res._op(error)
        }
    }
})

module.exports = router
